package com.huike.report.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;

import com.huike.report.domain.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.huike.business.mapper.TbBusinessMapper;
import com.huike.clues.domain.TbActivity;
import com.huike.clues.domain.TbAssignRecord;
import com.huike.clues.domain.TbClue;
import com.huike.clues.domain.vo.IndexStatisticsVo;
import com.huike.clues.mapper.SysDeptMapper;
import com.huike.clues.mapper.SysDictDataMapper;
import com.huike.clues.mapper.TbActivityMapper;
import com.huike.clues.mapper.TbAssignRecordMapper;
import com.huike.clues.mapper.TbClueMapper;
import com.huike.common.core.domain.entity.SysDept;
import com.huike.common.utils.SecurityUtils;
import com.huike.contract.domain.TbContract;
import com.huike.contract.mapper.TbContractMapper;
import com.huike.report.mapper.ReportMapper;
import com.huike.report.service.IReportService;

import javax.annotation.PostConstruct;

@Service
public class ReportServiceImpl implements IReportService {

    @Autowired
    private TbContractMapper contractMapper;


    @Autowired
    private SysDictDataMapper sysDictDataMapper;


    @Autowired
    private TbClueMapper clueMapper;

    @Autowired
    private TbActivityMapper activityMapper;

    @Autowired
    private TbBusinessMapper businessMapper;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private TbAssignRecordMapper assignRecordMapper;

    @Autowired
    private ReportMapper reportMpper;

/*    private static String username;

    @PostConstruct
    public void init(){
        username = SecurityUtils.getUsername();
    }*/

    @Override
    public LineChartVO contractStatistics(String beginCreateTime, String endCreateTime) {
        LineChartVO lineChartVo = new LineChartVO();
        try {
            List<String> timeList = findDates(beginCreateTime, endCreateTime);
            lineChartVo.setxAxis(timeList);
            List<LineSeriesVO> series = new ArrayList<>();
            List<Map<String, Object>> statistics = contractMapper.contractStatistics(beginCreateTime, endCreateTime);
            LineSeriesVO lineSeriesDTO1 = new LineSeriesVO();
            lineSeriesDTO1.setName("新增客户数");
            LineSeriesVO lineSeriesDTO2 = new LineSeriesVO();
            lineSeriesDTO2.setName("客户总数");
            int sum = 0;
            for (String s : timeList) {
                Optional optional = statistics.stream().filter(d -> d.get("dd").equals(s)).findFirst();
                if (optional.isPresent()) {
                    Map<String, Object> cuurentData = (Map<String, Object>) optional.get();
                    lineSeriesDTO1.getData().add(cuurentData.get("num"));
                    sum += Integer.parseInt(cuurentData.get("num").toString());
                } else {
                    lineSeriesDTO1.getData().add(0);
                }
                lineSeriesDTO2.getData().add(sum);
            }
            series.add(lineSeriesDTO1);
            series.add(lineSeriesDTO2);
            lineChartVo.setSeries(series);
        } catch (ParseException e) {
            // e.printStackTrace();
        }
        return lineChartVo;
    }

    @Override
    public LineChartVO salesStatistics(String beginCreateTime, String endCreateTime) {
        LineChartVO lineChartVo = new LineChartVO();
        try {
            List<String> timeList = findDates(beginCreateTime, endCreateTime);
            lineChartVo.setxAxis(timeList);
            List<LineSeriesVO> series = new ArrayList<>();
            List<Map<String, Object>> statistics = contractMapper.salesStatistics(beginCreateTime, endCreateTime);
            LineSeriesVO lineSeriesVo = new LineSeriesVO();
            lineSeriesVo.setName("销售统计");
            int sum = 0;
            for (String s : timeList) {
                Optional optional = statistics.stream().filter(d -> d.get("dd").equals(s)).findFirst();
                if (optional.isPresent()) {
                    Map<String, Object> cuurentData = (Map<String, Object>) optional.get();
                    lineSeriesVo.getData().add(cuurentData.get("sales"));
                } else {
                    lineSeriesVo.getData().add(0);
                }
            }
            series.add(lineSeriesVo);
            lineChartVo.setSeries(series);
        } catch (ParseException e) {
            // e.printStackTrace();
        }
        return lineChartVo;
    }


    /**
     * 渠道统计
     */
    @Override
    public List<Map<String, Object>> chanelStatistics(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data = contractMapper.chanelStatistics(beginCreateTime, endCreateTime);
        for (Map<String, Object> datum : data) {
            String subjectValue = (String) datum.get("channel");
            String lable = sysDictDataMapper.selectDictLabel("clues_item", subjectValue);
            datum.put("channel", lable);
        }
        return data;
    }

    @Override
    public List<TbContract> contractReportList(TbContract tbContract) {
        return contractMapper.selectTbContractList(tbContract);
    }


    @Override
    public List<Map<String, Object>> activityStatistics(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data = contractMapper.activityStatistics(beginCreateTime, endCreateTime);
        for (Map<String, Object> datum : data) {
            Long activityId = (Long) datum.get("activity_id");
            TbActivity tbActivity = activityMapper.selectTbActivityById(activityId);
            if (tbActivity == null) {
                datum.put("activity", "其他");
            } else {
                datum.put("activity", tbActivity.getName());
            }
        }
        return data;
    }

    /**
     * 按照部门统计销售
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public List<Map<String, Object>> deptStatisticsList(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data = contractMapper.deptStatistics(beginCreateTime, endCreateTime);
        for (Map<String, Object> datum : data) {
            Long deptId = (Long) datum.get("dept_id");
            if (deptId != null) {
                SysDept dept = deptMapper.selectDeptById(deptId);
                datum.put("deptName", dept.getDeptName());
            }
        }
        return data;
    }


    /**
     * 按照渠道统计销售
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public List<Map<String, Object>> channelStatisticsList(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data = contractMapper.channelStatistics(beginCreateTime, endCreateTime);
        for (Map<String, Object> datum : data) {
            String subjectValue = (String) datum.get("channel");
            if (subjectValue != null) {
                String lable = sysDictDataMapper.selectDictLabel("clues_item", subjectValue);
                datum.put("channel", lable);
            }
        }
        return data;
    }


    /**
     * 按照归属人统计销售
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public List<Map<String, Object>> ownerShipStatisticsList(String beginCreateTime, String endCreateTime) {
        return contractMapper.ownerShipStatistics(beginCreateTime, endCreateTime);
    }


    @Override
    public List<TbClue> cluesStatisticsList(TbClue clue) {
        return clueMapper.selectTbClueForReport(clue);
    }

    @Override
    public List<ActivityStatisticsVo> activityStatisticsList(TbActivity query) {
        query.setStatus("2");
        List<TbActivity> activities = activityMapper.selectTbActivityList(query);
        Map<String, Object> timeMap = query.getParams();
        List<ActivityStatisticsVo> list = new ArrayList<>();
        for (TbActivity activity : activities) {
            ActivityStatisticsVo dto = new ActivityStatisticsVo();
            BeanUtils.copyProperties(activity, dto);
            TbClue tbClue = new TbClue();
            tbClue.setActivityId(activity.getId());
            tbClue.setChannel(activity.getChannel());
            tbClue.setParams(timeMap);
            Map<String, Object> clueCount = clueMapper.countByActivity(tbClue);
            if (clueCount != null) {
                dto.setCluesNum(Integer.parseInt(clueCount.get("total").toString()));
                if (clueCount.get("falseClues") != null) {
                    dto.setFalseCluesNum(Integer.parseInt(clueCount.get("falseClues").toString()));
                }
                if (clueCount.get("toBusiness") != null) {
                    dto.setBusinessNum(Integer.parseInt(clueCount.get("toBusiness").toString()));
                }
            }
            TbContract tbContract = new TbContract();
            tbContract.setChannel(activity.getChannel());
            tbContract.setActivityId(activity.getId());
            tbContract.setParams(timeMap);
            Map<String, Object> contractCount = contractMapper.countByActivity(tbContract);
            if (contractCount != null) {
                dto.setCustomersNum(Integer.parseInt(contractCount.get("customersNum").toString()));
                if (contractCount.get("amount") == null) {
                    dto.setAmount(0d);
                } else {
                    dto.setAmount((Double) contractCount.get("amount"));
                }
                if (contractCount.get("cost") == null) {
                    dto.setCost(0d);
                } else {
                    dto.setCost((Double) contractCount.get("cost"));
                }

            }
            list.add(dto);
        }
        return list;
    }

    /**
     * *************看我看我**************
     * 传入两个时间范围，返回这两个时间范围内的所有时间，并保存在一个集合中
     *
     * @param beginTime
     * @param endTime
     * @return
     * @throws ParseException
     */
    public static List<String> findDates(String beginTime, String endTime)
            throws ParseException {
        List<String> allDate = new ArrayList();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date dBegin = sdf.parse(beginTime);
        Date dEnd = sdf.parse(endTime);
        allDate.add(sdf.format(dBegin));
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            allDate.add(sdf.format(calBegin.getTime()));
        }
        System.out.println("时间==" + allDate);
        return allDate;
    }


    @Override
    public IndexVo getIndex(IndexStatisticsVo request) {
        Long deptId = request.getDeptId();
        TbAssignRecord tbAssignRecord = new TbAssignRecord();
        tbAssignRecord.setLatest("1");
        assignRecordMapper.selectAssignRecordList(tbAssignRecord);
        return null;
    }

    @Override
    public List<Map<String, Object>> salesStatisticsForIndex(IndexStatisticsVo request) {
        List<Map<String, Object>> list = contractMapper.contractStatisticsByUser(request);
        for (Map<String, Object> datum : list) {
            Long deptId = (Long) datum.get("dept_id");
            if (deptId != null) {
                SysDept dept = deptMapper.selectDeptById(deptId);
                datum.put("deptName", dept.getDeptName());
            }
        }
        return list;
    }


    /**
     * ************看我看我***********
     * 用我能少走很多路
     * 我是用来机选百分比的方法
     *
     * @param all
     * @param num
     * @return
     */
    private BigDecimal getRadio(Integer all, Long num) {
        if (all.intValue() == 0) {
            return new BigDecimal(0);
        }
        BigDecimal numBigDecimal = new BigDecimal(num);
        BigDecimal allBigDecimal = new BigDecimal(all);
        BigDecimal divide = numBigDecimal.divide(allBigDecimal, 4, BigDecimal.ROUND_HALF_UP);
        return divide.multiply(new BigDecimal(100));
    }


    /**
     * 获取首页基本数据
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public IndexBaseInfoVO getBaseInfo(String beginCreateTime, String endCreateTime, String username) {
        //1）构建一个空的结果集对象
        IndexBaseInfoVO result = new IndexBaseInfoVO();
        //2 封装结果集属性
        // 2.1 由于查询需要用到用户名 调用工具类获取用户名
        //String username = SecurityUtils.getUsername();
//        3.异步封装
//        3.1 线程一：线索数量
        Integer cluesNum = reportMpper.getCluesNum(beginCreateTime, endCreateTime, username);
        System.out.println("线程一：" + Thread.currentThread().getId());
        result.setCluesNum(cluesNum);
//        3.2 开启异步线程
        CompletableFuture<IndexBaseInfoVO> c1 = CompletableFuture.supplyAsync(() -> {//supplyAsync方法是开启一个新的线程
//            线程二：今日商机数量
            Integer businessNum = reportMpper.getBusinessNum(beginCreateTime, endCreateTime, username);
            result.setBusinessNum(businessNum);
            System.out.println("线程二：" + Thread.currentThread().getId());
            return result;
        }).thenCombine(CompletableFuture.supplyAsync(() -> {
//            线程三：今日合同数量
            Integer contractNum = reportMpper.getContractNum(beginCreateTime, endCreateTime, username);
            System.out.println("线程三：" + Thread.currentThread().getId());
            return contractNum;
        }), (a, b) -> {//a:代表上一个线程的返回值，b：代表当thenCombine新开线程的返回值
            a.setContractNum(b);
            return a;
        }).thenCombine(CompletableFuture.supplyAsync(() -> {//thenCombine方法可以并发执行线程，并且使得上一个线程的结果可以和当前线程合并
//            线程四：盈利金额
            Double salesAmount = reportMpper.getSalesAmount(beginCreateTime, endCreateTime, username);
            System.out.println("线程四：" + Thread.currentThread().getId());
            return salesAmount;
        }), (c, d) -> {
            c.setSalesAmount(d);
            return c;
        });
//        c1.join()是将上述线程的组合结果返回
        BeanUtils.copyProperties(c1.join(), result);
        //4 返回结果集对象
        return result;
    }

    /**
     * @Description 获取今日简报信息
     * @Retrurn indexBaseInfoVO 保存了今日简报需要的信息
     */
/*    @Override
    public IndexTodayInfoVO getTodayInfo(String currentTime,String username) {
//      1.构建结果集用于保存四个结果
        IndexTodayInfoVO indexTodayInfoVO = new IndexTodayInfoVO();
//      2.获取当前登录用户的用户名
       // String username = SecurityUtils.getUsername();
//      3.对今日简报的数据的获取
//        3.1今日线索数量
        Integer todayCluesNum = reportMpper.getTodayCluesNum(currentTime, username);
//        System.out.println("新增线索数量："+todayCluesNum);
//        3.2今日商机数量
        Integer todayBusinessNum = reportMpper.getTodayBusinessNum(currentTime, username);
//        System.out.println("新增商机数量："+todayBusinessNum);
//        3.3今日新增客户数量
        Integer todayContractNum = reportMpper.getTodayContractNum(currentTime, username);
//        System.out.println("新增客户数量："+todayContractNum);
//        3.4今日收益
        Double todaySalesAmount = reportMpper.getTodaySalesAmount(currentTime, username);
//        System.out.println("今日收益："+todaySalesAmount);
//        4.封装数据
        indexTodayInfoVO.setTodayCluesNum(todayCluesNum);
        indexTodayInfoVO.setTodayBusinessNum(todayBusinessNum);
        indexTodayInfoVO.setTodayContractNum(todayContractNum);
        indexTodayInfoVO.setTodaySalesAmount(todaySalesAmount);
//        System.out.println("indexBaseInfoVO:"+indexTodayInfoVO.getTodayBusinessNum());
        return indexTodayInfoVO;
    }*/

    /**
     * @param currentTime
     * @param username
     * @return com.huike.report.domain.vo.IndexTodayInfoVO
     * @author chenqingxu
     * @description 今日简报的数据，新增线索，新增商机，今日客户，今日销售额。并且使用complateFuture异步编程加快数据的获取速度
     */
    @Override
    public IndexTodayInfoVO getTodayInfo(String currentTime, String username) {
//      1.构建结果集用于保存四个结果，使用vo实体类，vo实体类用于对应前端的各项数据，方便后端进行数据处理
        IndexTodayInfoVO indexTodayInfoVO = new IndexTodayInfoVO();
//      2.获取当前登录用户的用户名
        // String username = SecurityUtils.getUsername();
//      3.对今日简报的数据的获取
//        3.1 线程一：今日线索数量
        Integer todayCluesNum = reportMpper.getTodayCluesNum(currentTime, username);
        indexTodayInfoVO.setTodayCluesNum(todayCluesNum);
//        3.2 开启异步线程
        CompletableFuture<IndexTodayInfoVO> c1 = CompletableFuture.supplyAsync(() -> {
//            线程二：今日商机数量
            Integer todayBusinessNum = reportMpper.getTodayBusinessNum(currentTime, username);
            indexTodayInfoVO.setTodayBusinessNum(todayBusinessNum);
            return indexTodayInfoVO;
        }).thenCombine(CompletableFuture.supplyAsync(() -> { //thenCombine的使用，表示同时开启另一个线程执行人后
            //两个任务完成后再合并
//            线程三：今日合同数量
            Integer todayContractNum = reportMpper.getTodayContractNum(currentTime, username);
            return todayContractNum;
        }), (a, b) -> {   //开始合并两个线程的任务结果，a是线程二的结果，b是线程三的结果
            a.setTodayContractNum(b);
            return a;
        }).thenCombine(CompletableFuture.supplyAsync(() -> {
//            线程四：盈利金额
            Double todaySalesAmount = reportMpper.getTodaySalesAmount(currentTime, username);
            return todaySalesAmount;
        }), (c, d) -> {
            c.setTodaySalesAmount(d);
            return c;
        });
        BeanUtils.copyProperties(c1.join(), indexTodayInfoVO);

        return indexTodayInfoVO;
    }

    /**
     * @param beginCreateTime
     * @param endCreateTime
     * @param username
     * @return com.huike.report.domain.vo.IndexTodoInfoVO
     * @author chenqingxu
     * @description 获取代办事件的数据，依然使用异步编程complateFuture
     */
    public IndexTodoInfoVO getTodoInfo(String beginCreateTime, String endCreateTime, String username) {
//        依然使用vo实体类进行封装代办数据
        IndexTodoInfoVO indexTodoInfoVO = new IndexTodoInfoVO();
//        获取当前用户
        // String username = SecurityUtils.getUsername();
        System.out.println("用户：" + username);
        System.out.println("开始时间：" + beginCreateTime);
        System.out.println("结束时间：" + endCreateTime);
//        3.1 线程一：获取待分配线索
        Integer locatedClue = reportMpper.getLocatedClue(beginCreateTime, endCreateTime, username);
        indexTodoInfoVO.setToallocatedCluesNum(locatedClue);
//        3.2 开启异步线程
        CompletableFuture<IndexTodoInfoVO> c1 = CompletableFuture.supplyAsync(() -> {
//        获取待跟进线索
            Integer followClue = reportMpper.getFollowClue(beginCreateTime, endCreateTime, username);
            indexTodoInfoVO.setTofollowedCluesNum(followClue);
            return indexTodoInfoVO;
        }).thenCombine(CompletableFuture.supplyAsync(() -> {
//        获取待分配商机
            Integer locatedBusiness = reportMpper.getLocatedBusiness(beginCreateTime, endCreateTime, username);
            return locatedBusiness;
        }), (a, b) -> {
            a.setToallocatedBusinessNum(b);
            return a;
        }).thenCombine(CompletableFuture.supplyAsync(() -> {
//        获取待跟进商机
            Integer followBusiness = reportMpper.getFollowBusiness(beginCreateTime, endCreateTime, username);
            return followBusiness;
        }), (c, d) -> {
            c.setTofollowedBusinessNum(d);
            return c;
        });
        BeanUtils.copyProperties(c1.join(), indexTodoInfoVO);

        return indexTodoInfoVO;
    }
}